package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RequestMapping("/login")
@Controller
@ResponseBody
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private LoginService loginService;

    @RequestMapping("/telephoneLogin")
    public Result telephoneLogin(@RequestBody Map<String,String> map, HttpServletResponse response){
        String code = map.get("validateCode");
        if(code==null){
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        String telephone = map.get("telephone");
        Result result=loginService.telephoneLogin(telephone,code);
        //注册过返回登录成功的提示,并且需要将这个手机号信息存到cookie中待会浏览器，下次访问时不用再次登录
        Cookie cookie = new Cookie("telephone",telephone);
        cookie.setMaxAge(60*60*24*30);
        cookie.setPath("/");
        //将信息写到redis，半小时内不用重复登录,(phone为key,member为value)
        Member member = (Member) result.getData();
        jedisPool.getResource().setex(telephone,60*30, JSON.toJSON(member).toString());
        return result;
    }
}
